package com.dayaokeji.rhythmschoolstudent.utils;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;

import com.dayaokeji.imkitwrapper.init.ImKitWrapper;
import com.dayaokeji.rhythmschoolstudent.client.common.ActivityStackManager;
import com.dayaokeji.rhythmschoolstudent.client.common.base.App;
import com.dayaokeji.rhythmschoolstudent.client.mine.account.StudentIdLoginActivity;
import com.dayaokeji.rhythmschoolstudent.databases.dao.UserInfoDao;
import com.dayaokeji.rhythmschoolstudent.event.ExitEvent;
import com.dayaokeji.rhythmschoolstudent.service.AppStateService;
import com.dayaokeji.rhythmschoolstudent.service.AppUniqueIdService;
import com.dayaokeji.rhythmschoolstudent.service.MobileInfoCollectService;
import com.dayaokeji.server_api.domain.UserInfo;
import com.google.gson.Gson;

import org.greenrobot.eventbus.EventBus;

import java.util.Calendar;
import java.util.Date;

import cn.jpush.android.api.JPushInterface;

/**
 * Created by Gorden on 2017/9/28.
 * 用户信息帮助类
 */

public class UserUtils {

    private static final String PREF_NAME = "com.rhythmschool.user";
    private static final String KEY_USER_INFO = "user_info";
    private static final String KEY_ACCESS_TOKEN = "access_token";
    private static final String KEY_IM_TOKEN = "im_token";

    private static UserInfo userInfo;
    private static final Gson gson = new Gson();

    public static boolean checkLogin(final Context context) {
        boolean hashLogin = hashLogin();
        if (!hashLogin) {
            // 清除用户信息
            setAccessToken("");
            setUserInfo(null);
            ImKitWrapper.stopImService();
            stopService(context);
            UserInfoDao.delUserInfo();
            JPushInterface.setAlias(context, "", null);
            EventBus.getDefault().post(new ExitEvent());
            Intent intent = new Intent(context, StudentIdLoginActivity.class);
            context.startActivity(intent);
            if (context instanceof Activity) {
                ActivityStackManager.finish((Activity) context);
            }
        }
        return hashLogin;
    }

    public static boolean hashLogin() {
        return getAccessToken() != null && !TextUtils.isEmpty(getAccessToken()) && getUserInfo() != null;
    }

    public static void setUserInfo(UserInfo userInfo) {
        getPreferences().edit().putString(KEY_USER_INFO, gson.toJson(userInfo)).apply();
    }

    public static boolean isExpiresLogin() {
        Calendar instance = Calendar.getInstance();
        long expiresLoginTime = PrefUtils.getExporesLoginTime();
        instance.setTimeInMillis(expiresLoginTime);
        instance.add(Calendar.DAY_OF_MONTH, 29);
        Date time = instance.getTime();
        Date dayBegin = DateUtils.getDayBegin();
        return time.before(dayBegin);
    }

    @Nullable
    public static UserInfo getUserInfo() {
        String userInfoStr = getPreferences().getString(KEY_USER_INFO, null);
        if (!TextUtils.isEmpty(userInfoStr)) {
            userInfo = gson.fromJson(userInfoStr, UserInfo.class);
        }
        return userInfo;
    }

    /**
     * get uid
     * @return
     */
    public static long getCurrentUid() {
        UserInfo userInfo = getUserInfo();
        if (userInfo != null && userInfo.getId() != null) {
            return  Long.parseLong(userInfo.getId());
        }
        return 0;
    }

    @Nullable
    public static String getCurrentUserName() {
        UserInfo userInfo = getUserInfo();
        if (userInfo != null) {
            return userInfo.getName();
        }
        return "";
    }

    private static SharedPreferences getPreferences() {
        return App.getAppContext().getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
    }

    public static void setAccessToken(String token) {
        getPreferences().edit().putString(KEY_ACCESS_TOKEN,"Bearer "+token).apply();
    }

    @Nullable
    public static String getAccessToken() {
        return getPreferences().getString(KEY_ACCESS_TOKEN,null);
    }

    public static boolean checkIsStudent(Context context, UserInfo userInfo) {
        if (userInfo != null) {
            if (userInfo.getType() != 2) {
                // 清除用户信息
                setAccessToken(null);
                setUserInfo(null);
                UserInfoDao.delUserInfo();
                EventBus.getDefault().post(new ExitEvent());
                Intent intent = new Intent(context, StudentIdLoginActivity.class);
                context.startActivity(intent);
                ToastUtils.warning("您的帐号是教师帐号，请使用律动校园APP登录");
                return false;
            }else{
                return true;
            }
        }
        return false;
    }


    /**
     * 根据性别标识得到性别名称
     * @param gender
     * @return
     */
    public static String getGenderName(int gender) {
        switch (gender) {
            case 1:
                return "男";
            case 2:
                return "女";
            default:
                return "隐藏";
        }
    }

    /**
     * 设置 im token
     * @param token
     */
    public static void setImToken(@NonNull String token) {
        getPreferences().edit().putString(KEY_IM_TOKEN, token).apply();
    }

    /**
     * get im token
     * @return
     */
    @Nullable
    public static String getImToken() {
        return getPreferences().getString(KEY_IM_TOKEN,"");
    }


    /**
     * close all service
     * @param context
     */
    public static void stopService(@NonNull Context context) {
        context.stopService(new Intent(context, MobileInfoCollectService.class));
        context.stopService(new Intent(context, AppStateService.class));
        context.stopService(new Intent(context, AppUniqueIdService.class));
    }

}
